package org.smart4j.framework.helper;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.smart4j.framework.util.ArrayUtil;
import org.smart4j.framework.util.ReflectUtil;

/**
 * description: 依赖注入助手类
 * @version v1.0
 * @author w
 * @date 2018年8月31日下午5:20:04
 */
public final class IocHelper {
	@SuppressWarnings("unused")
	private IocHelper instanse = new IocHelper();
	
	static{
		// 获取所有Bean类和Bean实例之间的映射关系 （BEAN_MAP）
		Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
		if(beanMap != null && beanMap.size() > 0){
			Iterator<Entry<Class<?>, Object>> iterator = beanMap.entrySet().iterator();
			while(iterator.hasNext()){
				Entry<Class<?>, Object> next = iterator.next();
				Class<?> beanClass = next.getKey();
				Object beanInstanse = next.getValue();
				// 获取Bean类中的全部成员变量
				Field[] beanFields = beanClass.getDeclaredFields();
				if(ArrayUtil.isNotEmpty(beanFields)){
					for (Field field : beanFields) {
						// 获取 bean field 的数据类型
						Class<?> beanFieldClass = field.getType();
						Object beanFieldInstanse = beanMap.get(beanFieldClass);
						if(null != beanInstanse){
							// 使用反射对	bean field 属性值进行初始化
							ReflectUtil.setField(beanInstanse, field, beanFieldInstanse);
						}
					}
				}
			}
		}
	} // end static 
}
